<?php

function cable_adminEntryEdit()
{
	global $cable_admin_plugin;
	
	/* standard adminlevel check */
	if ($cable_admin_plugin[connector]->user->values[adminlevel] < 1)
		return true;
		
	/* switch the action template, and check for sanity */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-EntryPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving entry editing page';
		
	/* get the entry's timestamp */
	if ($_REQUEST['preview'])
		$timestamp = -1 * urldecode($_REQUEST['entry_timestamp']);
	else
		$timestamp = abs(urldecode($_REQUEST['entry_timestamp']));
		
	/* are we supposed to perform an action on the entry? */
	$load_attributes = true;
	switch (urldecode($_REQUEST['entry_action']))
	{
		case 'save_entry':
			if ($_REQUEST['preview']) /* use current time instead */
				$timestamp = -1 * time();
			else
				$timestamp = time();
				
			if (($ret = cable_adminEntrySave($timestamp)) !== true)
				return $ret;
			$load_attributes = false;
			break;
		case 'save_edits':
			if (($ret = cable_adminEntrySave($timestamp)) !== true)
				return $ret;
			$load_attributes = false;
			break;
		default: /* opening an entry for editing for the first time */
			$cable_admin_plugin[action_template]->SetBool('CABLE-New',false);
			$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',true);
			break;
	}

	/* retrieve (possibly modified) entry data */
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_entries";
	if ($cable_admin_plugin[connector]->user->values['adminlevel'] > 1)
		$query = "SELECT * FROM $table WHERE (timestamp = '$timestamp') LIMIT 1";
	else
		$query = "SELECT * FROM $table WHERE (timestamp = '$timestamp') AND (author = '".$cable_admin_plugin[connector]->user->values[username]."') LIMIT 1";
	
	if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
	{
		/* if we couldn't load an entry, load whatever we have from post variables back into the form */
		if (mysql_num_rows($result) == 0)
		{
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.timestamp',$timestamp);
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.title',htmlspecialchars(stripslashes(urldecode($_REQUEST['entry_title']))));
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.text',htmlspecialchars(stripslashes(urldecode($_REQUEST['entry_text']))));
		}
		else
		{
			$entry_data = mysql_fetch_assoc($result);
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.timestamp',abs($timestamp));
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.title',htmlspecialchars(rawurldecode($entry_data['title'])));
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.author',htmlspecialchars(rawurldecode($entry_data['author'])));
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.text',htmlspecialchars(rawurldecode($entry_data['text'])));
		}
		
		/* set entry attributes, if they haven't already been loaded */
		if ($load_attributes)
			if (($ret = cable_adminEntryAttributes(unserialize($entry_data['data']))) !== true)
				return $ret;
	}
	
	/* delete any temporary preview entries other than the current one (if any) */
	$query = "DELETE FROM $table WHERE (timestamp < 0) AND (timestamp != '$timestamp') AND (author='".$cable_admin_plugin[connector]->user->values[username]."')";
	mysql_query($query,$cable_admin_plugin[connector]->db_link);

	return true;
}

function cable_adminEntrySave($timestamp)
{
	global $cable_admin_plugin;
	
	/* build the entry attributes */
	if (($ret = cable_adminEntryAttributes()) !== true)
		return $ret;
	
	/* generate database-ready versions of the entry data */
	$author	= $cable_admin_plugin[connector]->user->values[username];
	$title	= rawurlencode(stripslashes(urldecode($_REQUEST['entry_title'])));
	$text	= rawurlencode(stripslashes(urldecode($_REQUEST['entry_text'])));
	$data	= serialize($cable_admin_plugin[attribute_list]);
	$visible = (int) $cable_admin_plugin[attribute_list][visible];

	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_entries";
	$error = false;
	switch (urldecode($_REQUEST['entry_action']))
	{
		case 'save_entry': /* save a new entry */
			if (($_REQUEST['remove_attribute'] == '') && ($_REQUEST['add_attribute'] == '')) /* don't run database query for adding/subtracting attributes */
			{
				$query = "INSERT INTO $table (timestamp,author,title,text,data,visible) VALUES ('$timestamp','$author','$title','$text','$data','$visible')";
				if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === true)
				{
					if ($_REQUEST['preview'] == '')
					{
						$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
						$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','Entry successfully saved');
	
						/* change template bools to reflect that entry was succesfully saved */
						$cable_admin_plugin[action_template]->SetBool('CABLE-New',false);
						$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',true);
					}
					else /* we're previewing an entry */
					{
						/* change template bools to reflect that entry hasn't been saved yet */
						$cable_admin_plugin[action_template]->SetBool('CABLE-New',true);
						$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',false);
					}
				}
				else /* threw an error on inserting into the database */
				{
					if ($_REQUEST['preview'])
						$error = 'Preview could not be generated';
					else
						$error = 'Entry could not be saved';
						
					$cable_admin_plugin[action_template]->SetBool('CABLE-New',true); /* change template bools to reflect that entry was not saved */
					$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',false);
				}
			}
			else
			{
				$cable_admin_plugin[action_template]->SetBool('CABLE-New',true);
				$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',false);
			}
			break;
		case 'save_edits': /* save edits to an existing entry */
			if (($_REQUEST['remove_attribute'] == '') && ($_REQUEST['add_attribute'] == '')) /* don't run database query for adding/subtracting attributes */
			{
				$query = "REPLACE INTO $table (timestamp,author,title,text,data,visible) VALUES ('$timestamp','$author','$title','$text','$data','$visible')";
				if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) === true)
				{
					if ($_REQUEST['preview'] == '')
					{
						$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
						$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','Entry edits successfully saved');
					}
				}
				else
				{
					if ($_REQUEST['preview'])
						$error = 'Preview could not be generated';
					else
						$error = 'Entry edits could not be saved.';
				}
			}

			$cable_admin_plugin[action_template]->SetBool('CABLE-New',false);
			$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',true);
			
			break;	
	}
	
	if ($error !== false)
	{
		/* fill out error text */
		$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text',$error);
		
		/* replace template variables with HTML-friendly version of the title and text */
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.timestamp',$timestamp);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.title',htmlspecialchars(stripslashes(urldecode($_REQUEST['entry_title']))));
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.text',htmlspecialchars(stripslashes(urldecode($_REQUEST['entry_text']))));
	}
	elseif ($_REQUEST['preview'])
	{
			$cable_admin_plugin[action_template]->SetBool('CABLE-Preview',true);
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Preview.url',$cable_admin_plugin[connector]->config[SiteURL].'entry.php?t='.$timestamp);
	}
	
	return true;
}


function cable_adminEntryNew()
{
	global $cable_admin_plugin;
	
	/* switch to the signup template, and check for sanity */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-EntryPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving entry editing page';

	/* set the appropriate template booleans */
	$cable_admin_plugin[action_template]->SetBool('CABLE-New',true);
	$cable_admin_plugin[action_template]->SetBool('CABLE-Edit',false);
	
	return cable_adminEntryAttributes();
}

function cable_adminEntryAttributes($attributes=array())
{
	global $cable_admin_plugin;
	
	/* if we've been passed any attributes, load those to the internal array */
	$attribute_list = $attributes;

	/* generate attribute list from present returned values */
	foreach($_REQUEST as $request_name => $request_value)
	{
		if (strpos($request_name,'attribute_type_') !== false)
		{
			$attribute_type = $request_value;
			$attribute_name = str_replace('attribute_type_','',$request_name);
			$attribute_value = $_REQUEST['attribute_'.$attribute_name];

			/* if the attribute isn't already present in the attribute list, add it */
			if (!$attribute_list[$attribute_name])
			{
				switch ($attribute_type)
				{
					case 'array':
						$attribute_list[$attribute_name] = explode(',',$attribute_value);
						break;
					case 'boolean':
						$attribute_list[$attribute_name] = (bool)$attribute_value;
						break;
					case 'number':
					case 'string':
						$attribute_list[$attribute_name] = rawurlencode($attribute_value);
						break;
				}
			}
		}
	}
	
	/* add extra attributes if requested */
	if ($_REQUEST['entry_newattribute_type'] !== '')
	{
		$attribute_name = urldecode($_REQUEST['entry_newattribute_name']);
		switch (urldecode($_REQUEST['entry_newattribute_type']))
		{
			case 'array':
				$attribute_list[$attribute_name] = array();
				break;
			case 'boolean':
				$attribute_list[$attribute_name] = false;
				break;
			case 'number':
				$attribute_list[$attribute_name] = 0;
				break;
			case 'string':
				$attribute_list[$attribute_name] = '';
				break;
		}
	}

	/* remove any attributes if requested */
	if ($_REQUEST['remove_attribute'] != '')
		unset($attribute_list[urldecode($_REQUEST['remove_attribute'])]);
	
	/* make sure the default entry attributes are in the attribute list */
	$default_attributes = array();
	foreach($cable_admin_plugin[connector]->config['DefaultEntryAttributes'] as $default_attribute)
	{
		$array = explode(',',$default_attribute);
		switch($array[1])
		{
			case 'array':
				if (!isset($attribute_list[$array[0]]))
					$attribute_list[$array[0]] = array_slice($array,2);
				break;
			case 'boolean':
				if (!isset($attribute_list[$array[0]]))
					$attribute_list[$array[0]] = (bool)$array[2];
				break;
			case 'number':
			case 'string':
				if (!isset($attribute_list[$array[0]]))
					$attribute_list[$array[0]] = rawurlencode($array[2]);
				break;
		}
		$default_attributes[] = $array[0];
	}

	/* finally, sort the attributes by key */
	ksort($attribute_list);
		
	/* retrieve attribute templates and check for existence */
	$bool_template = $cable_admin_plugin[action_template]->GetChild('CABLE-BooleanAttribute');
	if ($bool_template === false)
		return 'Error: could not retrieve boolean attribute template';
	$string_template = $cable_admin_plugin[action_template]->GetChild('CABLE-StringAttribute');
	if ($string_template === false)
		return 'Error: could not retrieve string attribute template';
	
	foreach($attribute_list as $attribute_name => $attribute_value)
	{
		/* most common is the string template, so go ahead and load that */
		$attribute_template = $string_template;
		if (is_array($attribute_value))
		{
			$attribute_value = htmlspecialchars(implode(',',$attribute_value));
			$attribute_template->ReplaceInsert('CABLE-Attribute.type','array');
		}
		elseif(is_bool($attribute_value)) // boolean
		{
			/* set the attribute template to the boolean one, since we previously assumed it'd be a string template */
			$attribute_template = $bool_template;
			$attribute_value = (bool)rawurldecode($attribute_value);
			$attribute_template->SetBool('CABLE-Attribute.value',$attribute_value);
			$attribute_template->ReplaceInsert('CABLE-Attribute.type','boolean');
		}
		elseif(is_numeric($attribute_value)) // number
		{
			$attribute_value = stripslashes(rawurldecode($attribute_value));
			$attribute_template->ReplaceInsert('CABLE-Attribute.type','number');
		}
		else // string
		{
			$attribute_value = htmlspecialchars(stripslashes(rawurldecode($attribute_value)));
			$attribute_template->ReplaceInsert('CABLE-Attribute.type','string');
		}
		
		$attribute_template->SetBool('CABLE-Attribute.default',in_array($attribute_name,$default_attributes));
		$attribute_template->ReplaceInsert('CABLE-Attribute.name',$attribute_name);
		$attribute_template->ReplaceInsert('CABLE-Attribute.value',$attribute_value);
		$cable_admin_plugin[action_template]->AppendInsert('CABLE-Attributes',$attribute_template->template);
		
		/* reset back to its like-new status whatever template we used */
		$attribute_template->Reset();
	}
	
	$cable_admin_plugin[attribute_list] = $attribute_list;
	return true;
}

function cable_adminEntryDelete()
{
	global $cable_admin_plugin;
	
	/* standard adminlevel check */
	if ($cable_admin_plugin[connector]->user->values[adminlevel] < 1)
		return true;
	
	/* switch the action template to the correct page */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-EntryDeletionPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving entry deletion page';
		
	/* get and sanitize entry information */
	$timestamp = (int) $_REQUEST['entry_timestamp'];
	$username = $cable_admin_plugin[connector]->user->values[username];
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_entries";
		
	if (($_REQUEST['entry_timestamp'] != '') && ($_REQUEST['entry_confirm'] != ''))
	{
		if ($cable_admin_plugin[connector]->user->values[adminlevel] > 1) /* superuser */
			$query = "DELETE FROM $table WHERE timestamp=$timestamp LIMIT 1";
		else
			$query = "DELETE FROM $table WHERE timestamp=$timestamp AND author='$username' LIMIT 1";
			
		if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
		{
			$cable_admin_plugin[action_template]->SetBool('CABLE-Notice',true);
			$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Notice.text','Entry successfully deleted');
		}
		else
			return 'Error deleting entry from database';
			
		$cable_admin_plugin[action_template]->SetBool('CABLE-Confirm',false);
	}
	elseif (($_REQUEST['entry_timestamp'] != '') && ($_REQUEST['entry_confirm'] == ''))
	{
		if ($cable_admin_plugin[connector]->user->values[adminlevel] > 1) /* superuser */
			$query = "SELECT title FROM $table WHERE timestamp=$timestamp LIMIT 1";
		else
			$query = "SELECT title FROM $table WHERE timestamp=$timestamp AND author='$username' LIMIT 1";
		
		if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
		{
			if (mysql_num_rows($result) > 0)
			{
				$array = mysql_fetch_assoc($result);
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.title',rawurldecode($array[title]));
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entry.timestamp',$timestamp);
				$cable_admin_plugin[action_template]->SetBool('CABLE-Confirm',true);
			}
			else
			{
				$cable_admin_plugin[action_template]->SetBool('CABLE-Error',true);
				$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Error.text','Invalid entry timestamp');
				$cable_admin_plugin[action_template]->SetBool('CABLE-Confirm',false);
			}
		}
		else
			return 'Error retreving entry information from database';
	}
	else
		$cable_admin_plugin[action_template]->SetBool('CABLE-Confirm',false);

	return true;	
}

function cable_adminEntryList()
{
	global $cable_admin_plugin;

	/* if the user isn't admin, drop out immediately */
	if ($cable_admin_plugin[connector]->user->values[adminlevel] < 1)
		return true;
	
	/* switch the action template to the correct page */
	$cable_admin_plugin[action_template] = $cable_admin_plugin[action_template]->GetChild('CABLE-EntriesPage');
	if ($cable_admin_plugin[action_template] === false)
		return 'Error retrieving entry list page';
		
	$entry_template = $cable_admin_plugin[action_template]->GetChild('CABLE-Entry');
	if ($entry_template === false)
		return 'Error retrieving entry list item template';
		
	/* retrieve the date formats */
	$date_formats = $cable_admin_plugin[action_template]->GetValue('CABLE-DateFormat',true);
	if (count($date_formats) == 0)
		$date_formats = array();
	
	/* get author whose entries we're to display */
	if ($_REQUEST['entry_author'] != '')
		$author = str_replace('"','',str_replace('\'','',urldecode($_REQUEST['entry_author'])));
	else
		$author = $cable_admin_plugin[connector]->user->values[username];
	
	/* get the latest timestamp we are to show */
	if ($_REQUEST['entry_timestamp'] != '')
		$timestamp = (int) urldecode($_REQUEST['entry_timestamp']);
	else
		$timestamp = time();
	
	/* fill out the authors selection list of the template */
	if (($ret = CABLE_adminAuthors($author)) !== true)
		return $ret;
		
	/* build the table name on which to execute the query */
	$table = "cable_".$cable_admin_plugin[connector]->config['TablePrefix']."_entries";
		
	/* retrieve entries from database */
	$last_entry = time();
	$first_entry = time();
	$query = "SELECT timestamp,title FROM $table WHERE (timestamp<$timestamp) AND (author='$author') ORDER BY timestamp DESC LIMIT ".((int)$cable_admin_plugin[connector]->config[EntryListCount]);
	if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
	{
		$counter = 0;
		while(($array = mysql_fetch_assoc($result)) !== false)
		{
			if ($counter == 0)
				$first_entry = $array[timestamp];
			
			foreach($date_formats as $i => $f)
				$entry_template->ReplaceInsert('CABLE-Entry.date.'.$i,date($f,$array[timestamp]));
				
			$entry_template->ReplaceInsert('CABLE-Entry.timestamp',$array[timestamp]);
			$entry_template->ReplaceInsert('CABLE-Entry.title',stripslashes(rawurldecode($array[title])));
			$cable_admin_plugin[action_template]->AppendInsert('CABLE-Entries',$entry_template->template);
			
			$last_entry = $array[timestamp];
			$entry_template->Reset();
			$counter++;
		}
	}
	else
		return 'Error accessing entry database table';
		
	/* do global replacements */
	$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entries.author',$author);
	
	/* format boundary dates and insert */
	foreach($date_formats as $i => $f)
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entries.first.date.'.$i,date($f,$first_entry));
	
	foreach($date_formats as $i => $f)
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entries.last.date.'.$i,date($f,$last_entry));	
	
	/* navigation, next entries */
	$query = "SELECT timestamp FROM $table WHERE (timestamp>$timestamp) AND (author='$author') ORDER BY timestamp DESC LIMIT 1";
	if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
	{
		$row = mysql_fetch_row($result);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Entries.nav.next',mysql_num_rows($result) > 0);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entries.nav.next',$row[0]);
	}
	
	/* navigation, previous entries */
	$query = "SELECT timestamp FROM $table WHERE (timestamp<$last_entry) AND (author='$author') ORDER BY timestamp DESC LIMIT 1";
	if(($result = mysql_query($query,$cable_admin_plugin[connector]->db_link)) !== false)
	{
		$row = mysql_fetch_row($result);
		$cable_admin_plugin[action_template]->SetBool('CABLE-Entries.nav.prev',mysql_num_rows($result) > 0);
		$cable_admin_plugin[action_template]->ReplaceInsert('CABLE-Entries.nav.prev',$row[0]);
	}

	return true;
}

?>